package com.ybear.demo;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.ybear.ybcomponent.ItemStyleBuild;
import com.ybear.ybcomponent.base.adapter.listener.OnMultiSelectChangeAdapter;
import com.ybear.ybcomponent.widget.ItemSwipeLayout;
import com.ybear.ybcomponent.widget.ToolbarView;
import com.ybear.ybcomponent.widget.menu.MenuItem;
import com.ybear.ybcomponent.widget.menu.MenuView;
import com.ybear.ybcomponent.widget.menu.OnCheckedChangeListener;
import com.ybear.ybnetworkutil.call.CallReqAdapter;
import com.ybear.ybnetworkutil.http.HttpClient;
import com.ybear.ybnetworkutil.network.NetworkChangeManage;
import com.ybear.ybutils.utils.IOUtil;
import com.ybear.ybutils.utils.LogUtil;
import com.ybear.ybutils.utils.StackManage;
import com.ybear.ybutils.utils.Utils;
import com.ybear.ybutils.utils.dialog.Dialog;
import com.ybear.ybutils.utils.handler.HandlerManage;
import com.ybear.ybutils.utils.notification.NotificationX;
import com.ybear.ybutils.utils.time.DateTime;
import com.ybear.ybutils.utils.toast.ToastManage;
import com.ybear.ybutils.utils.toast.ToastX;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import okhttp3.Call;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private int maxCount = 10;
    private AtomicInteger count = new AtomicInteger( 0 );
    private AtomicInteger timeCount = new AtomicInteger( 0 );

    private Context context = this;
    private ToastX mToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LogUtil.setDebugEnable( this, true );
        LogUtil.setCallLogEnable( true );
        LogUtil.setTagOfGlobal("TestTAG");
        LogUtil.setOnCallListener((tag, message, type) -> {
            //保存日志
            IOUtil.saveLogFile(
                    context, String.format("TAG:%s | msg:%s | type:%s", tag, message, type)
            );
        });

        mToast = ToastManage.get().makeText( this );
        mToast.setText( "DEBUG: " + LogUtil.isDebug()).show();

        /* 时间转换 */
        LogUtil.e("TAG", "Time -> " +
                DateTime.parse( 1592474989 ) + " | " +
                DateTime.parse( DateTime.currentTimeMillis() ) + " | " +
                DateTime.parseOfList( DateTime.currentTimeMillis() ) + " | " +
                DateTime.now() + " | " +
                DateTime.nowOfList()
        );

//        Dialog.getInit().setDefTitleColorInt( Color.CYAN );
        Dialog.with( this )
                .setTitle("测试的标题")
                .setMessage("测试的内容")
                .setOnPositiveButtonListener((dialog, which) -> {
                    dialog.dismiss();
                    ToastManage.get().showToast(context, "确定按钮");
                }).setOnNegativeButtonListener("关闭对话框", (dialog, which) -> {
                    dialog.dismiss();
                    ToastManage.get().showToast(context, "关闭了对话框");
                }).create().show();

        ToolbarView tbv = findViewById(R.id.toolbar);
        tbv.setOtherBtnOfImg(R.drawable.ic_toolbar_back);
        tbv.showOtherBtnOfImg( true );

        MenuView menuView = findViewById(R.id.main_menu);
        menuView.setItemStyle(new ItemStyleBuild()
                .setIconSize( 60 )
                .setTextColor(R.color.colorAccent)
                .setTextSelectColor(R.color.colorPrimary)
        );

        menuView.setMenuItem(
                new MenuItem(
                        getResources(), R.mipmap.ic_launcher, "选项1", R.mipmap.ic_launcher, "选中1"
                ),
                new MenuItem(
                        getResources(), R.mipmap.ic_launcher, "", R.mipmap.ic_launcher, "选中2"
                ),
                new MenuItem(
                        getResources(), R.mipmap.ic_launcher, "", R.mipmap.ic_launcher, "选中3"
                ),
                new MenuItem(
                        getResources(), R.mipmap.ic_launcher, "选项4", R.mipmap.ic_launcher, "选中4"
                )
        );

        menuView.setEnableRedDot( true );
//        menuView.setRedDotSize( 20 );
        menuView.getRedDotLayout( 0 ).setTextSize( 12 ).setText( "9" );
        menuView.setBackgroundColor( Color.WHITE );
        menuView.setEnableTopLine( true );
        menuView.setTopLineHeight(Utils.dp2Px( this, 2 ) );
        menuView.setTopLineColor( Color.BLACK );
        menuView.notifyMenuChanged();

        menuView.setOnCheckedChangeListener( new OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(MenuView view, View v, int curPos, int oldPos) {
                LogUtil.e("TAG", "id " + curPos);
            }
        } );

        ItemSwipeLayout isLayout = findViewById(R.id.main_isl_item_swipe);
        isLayout.setEnableSwipeDrag( true );
        View[] views = new View[3];
        int[] colors = { R.color.colorAccent, R.color.colorPrimary, R.color.colorPrimaryDark };
        for (int i = 0; i < views.length; i++) {
            TextView tv = new TextView( this );
            tv.setText( ( "测试" + i ) );
            tv.setBackgroundResource( colors[i] );
            tv.setGravity(Gravity.CENTER);
            views[ i ] = tv;
        }
        isLayout.setSwipeViews( views );
        isLayout.setEnableMultiSwipeDrag( false );
        isLayout.setOnSwipeItemClickListener(new ItemSwipeLayout.OnSwipeItemClickListener() {
            @Override
            public void onClick(ItemSwipeLayout view, View childView, int position) {
                LogUtil.e("TAG", position + " " + childView);
            }
        });

        isLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtil.e("TAG", "OnClick:" + view);
            }
        });

//        isLayout.getItemView().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                LogUtil.e("TAG", view + "");
//            }
//        });

        RecyclerView rv = findViewById(R.id.rv_list);
        rv.setLayoutManager( new LinearLayoutManager( this ) );
        List<TestRvAdapter.TestData> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add( new TestRvAdapter.TestData().setName( "测试 " + i ) );
        }
        TestRvAdapter mAdapter = new TestRvAdapter( list );
//        mAdapter.setEnableMultiSelect( false );
        mAdapter.setReplaceLastSelect( true );
        mAdapter.setMaxMultiSelectCount( 5 );
        mAdapter.setMinMultiSelectCount( 2 );
//        mAdapter.setItemClickType( ItemClickType.SWITCH );

//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                mAdapter.setMultiSelectStatusOfFirst( 4, true );
//            }
//        }, 6000);


        rv.setAdapter( mAdapter );

        Button btnSelectAll = findViewById(R.id.rv_all_btn);
        btnSelectAll.setOnClickListener(v -> mAdapter.switchMultiSelectStatusAll());

        mAdapter.setOnMultiSelectChangeListener(new OnMultiSelectChangeAdapter
                <TestRvAdapter.TestHolder>() {
            @Override
            public void onMultiSelectAll(RecyclerView.Adapter<TestRvAdapter.TestHolder> adapter,
                                         boolean isSelectAll, boolean fromUser) {
                btnSelectAll.setText( isSelectAll ? "反选" : "全选" );
            }
        });

        //点击事件
        mAdapter.setOnItemClickListener((adapter, v, data, position) -> {
            LogUtil.e("TAG", "Click -> " + position);
            ToastManage.get().showToast(v.getContext(), "点击事件：" + position);
        });

        //长按事件
        mAdapter.setOnItemLongClickListener((adapter1, v, data, position) -> {
            LogUtil.e("TAG", "LongClick -> " + position);
            ToastManage.get().showToast(v.getContext(), "长按事件：" + position);
            return false;
        });

        ViewPager pager = findViewById(R.id.rv_pager);
        List<TestRvPagerAdapter.ItemData> pagerList = new ArrayList<>();
        for (int i = 1; i <= 20000; i++) {
            pagerList.add(new TestRvPagerAdapter.ItemData().setTitle("测试页面 " + i));
        }
        TestRvPagerAdapter pagerAdapter = new TestRvPagerAdapter( pagerList );
        pager.setAdapter( pagerAdapter );

        pager.setOffscreenPageLimit( 5 );
        pager.setCurrentItem( 19999 );

        HttpClient.create().build().addReqDataListener(new CallReqAdapter(){
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response r) throws IOException {
                super.onResponse(call, r);
                LogUtil.d("TAG", "r: " + r.toString());
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                super.onFailure(call, e);
                LogUtil.d("TAG", "f: " + e.getMessage());
            }
        } ).req("https://haokan.baidu.com/v?vid=17417821379914441855&tab=").get();

        LogUtil.e("TAG", "111 -> " + IOUtil.saveFile( getExternalFilesDir(null).getAbsolutePath(), "aaa.txt", "111".getBytes()) );
        HandlerManage.create().post( () -> LogUtil.e(
                "TAG",
                "222 -> " + IOUtil.saveFile( getExternalFilesDir(null).getAbsolutePath(),
                        "aaa.txt",
                        "222".getBytes(), true) ),
                1000
        );

        /* 展示一条通知 */
        HandlerManage.create().post( () -> {
            Intent intent = new Intent( this, TestActivity.class );
            boolean notifyResult = NotificationX.get()
                    .showNotification( hashCode(), "测试标题", "测试内容", intent, false );

            ToastManage.get().showToast( this, "展示通知结果：" + notifyResult );
        } );

    }

    @Override
    protected void onResume() {
        super.onResume();
        NetworkChangeManage ncm = NetworkChangeManage.get();
        if( !ncm.isRunningService() ) {
            ncm.registerService();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //除了MainActivity之外，没有其他页面时，解除注册服务
        if( !StackManage.get().isHaveExistActivityOfSkip( "MainActivity" ) ) {
            NetworkChangeManage.get().unregisterService();
        }
    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        NetworkChangeManage.get().unregisterService();
//    }
}
